use std::net::UdpSocket;
use std::net::Ipv4Addr;
use std::time::{Duration, SystemTime};
use std::{thread, time};


fn crt_udp(bindAddr: &str, ipv4group: Ipv4Addr) -> UdpSocket {
    let mut socket = UdpSocket::bind(bindAddr).unwrap();
    let mut buf = [0u8; 65535];
    let multi_addr = ipv4group;
    let inter = Ipv4Addr::new(0, 0, 0, 0);
    socket.join_multicast_v4(&multi_addr, &inter);
    println!("suc!");
    println!("looping sending...");

    loop {
        socket.send(&[1, 2, 3]);
        let (amt, src) = socket.recv_from(&mut buf).unwrap();
        println!("receive the msg--->>>amt = {:?}, src={:?}", amt, src);
    }
    return socket;
}

struct SmartCon {
    udp: UdpSocket
}

impl SmartCon {
    fn send_msg(&self) {
        println!("send once...");
        self.udp.send(&[1, 2, 3, 4]);
        thread::sleep(Duration::from_secs(1));
    }

    fn start(&self) {
        loop {
            let ten_millis = time::Duration::from_secs(1);
            let now = time::Instant::now();

            thread::sleep(ten_millis);
            self.send_msg();
        }
    }


    pub fn new() -> Self {
        println!("start udp svr...");
        let own_bind = "0.0.0.0:8002";
        let mulit_addr = Ipv4Addr::new(234, 2, 2, 2);
        SmartCon {
            udp: crt_udp(own_bind, mulit_addr)
        }
    }
}

fn test_udp() {
    let socket = UdpSocket::bind("127.0.0.1:8080").unwrap();

    loop {
        let mut buf = [0u8; 1500];
        let (amt, src) = socket.recv_from(&mut buf).unwrap();

        let buf = &mut buf[..amt];
        buf.reverse();
        socket.send_to(buf, &src);
    }
}

fn main() {
    // test_udp();
    let con = SmartCon::new();
    con.start();
}
